import { useState } from "react";
import { initialTravelPlan } from "./Places";
import { Button } from "antd";

// 定义Place接口，确保与initialTravelPlan结构一致
interface Place {
	id : number;
	title : string;
	childIds : number[];
	// 其他字段可根据实际数据添加
}

type PlacesById = Record<number, Place>;

const PlaceTree = (
	{
		id,
		parentId,
		onComplete,
		placesById
	} : { id : number, parentId : number, onComplete : ( parentId : number, childId : number ) => void, placesById : PlacesById }
) => {
	const place = placesById[id];
	const childIds = place.childIds;
	return (
		<li style={ { lineHeight : '2em' } } >
			{ place.title }
			<Button type="primary" size="small" style={ { marginLeft : '10px' } } onClick={ () => onComplete( parentId, id ) } >Complete</Button >
			{ childIds.length > 0 && (
				<ol style={ { lineHeight : '2em' } } >
					{ childIds.map( childId => (
						<PlaceTree
							key={ childId }
							id={ childId }
							parentId={ id }
							placesById={ placesById }
							onComplete={ onComplete }
						/>
					) ) }
				</ol >
			) }
		</li >
	);
}

type Plan = Record<number, Place>;
const TravelPlan = () => {
	const [ plan, setPlan ] = useState<Plan>( initialTravelPlan );
	const root = plan[0];
	const planetIds = root.childIds;
	const handleComplete = ( parentId : number, childId : number ) => {
		const parent = plan[parentId];
		if( !parent ) return; // 防止 parentId 不存在
		const nextPlan = {
			...parent,
			childIds : parent.childIds.filter( ( id : number ) => id !== childId ),
		};
		setPlan( {
			...plan,
			[parentId] : nextPlan,
		} );


	};
	return (
		<>
			<h2 >Places to visit</h2 >
			<ol >
				{ planetIds.map( id => (
					<PlaceTree
						key={ id }
						id={ id }
						placesById={ plan }
						parentId={ 0 }
						onComplete={ handleComplete }
					/>
				) ) }
			</ol >
		</>
	);
};

export default TravelPlan;